package com.mls.wms.android.widget.outwh;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.http.RequestManager;
import com.google.zxing.client.android.Intents;
import com.mls.wms.android.R;
import com.mls.wms.android.constant.ScanTypeConstants;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseActivity;
import com.mls.wms.android.model.PickShipOrderModel;
import com.mls.wms.android.model.ResponseResult;
import com.mls.wms.android.util.DialogUtils;
import com.mls.wms.android.util.ViewUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2015-09-02.
 */
public class PickToSortActivity extends BaseActivity {
    private long waveId = 0L;
    private String shipmentId = "";
    private long containerId = 0L;
    private long locationId = 0L;
    private long skuId = 0L;

    private EditText txtPickCarNo = null;
    private EditText txtSpecLocationNo = null;
    private EditText txtNextLocationNo = null;
    private EditText txtSpecBarcode = null;
    private EditText txtItemName = null;
    private EditText txtPickingQty = null;
    private EditText txtRealLocationNo = null;
    private EditText txtItemBarcode = null;
    private EditText txtPickedQty = null;

    private LinearLayout layoutQty = null;

    private Button btnContinue = null;
    private Button btnMissing = null;

    private EditText selectEt = null;
    private AnimDialogFragment progressDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_pick_to_sort);

        //弹出框
        progressDialog = new AnimDialogFragment();
        progressDialog.setResId(R.drawable.anim_progress_dialog);

        this.layoutQty = (LinearLayout) this.findViewById(R.id.act_pick_to_sort_layout_qty);

        this.txtPickCarNo = (EditText) this.findViewById(R.id.act_pick_to_sort_txt_pick_car_no);
        this.txtSpecLocationNo = (EditText) this.findViewById(R.id.act_pick_to_sort_txt_spec_location_no);
        this.txtNextLocationNo = (EditText) this.findViewById(R.id.act_pick_to_sort_txt_next_location_no);
        this.txtSpecBarcode = (EditText) this.findViewById(R.id.act_pick_to_sort_txt_spec_item_barcode);
        this.txtItemName = (EditText) this.findViewById(R.id.act_pick_to_sort_txt_spec_item_name);
        this.txtPickingQty = (EditText) this.findViewById(R.id.act_pick_to_sort_txt_picking_qty);
        this.txtRealLocationNo = (EditText) this.findViewById(R.id.act_pick_to_sort_txt_real_location_no);
        this.txtItemBarcode = (EditText) this.findViewById(R.id.act_pick_to_sort_txt_item_barcode);
        this.txtPickedQty = (EditText) this.findViewById(R.id.act_pick_to_sort_txt_picked_qty);
        this.txtPickedQty.setText("1");

        this.btnContinue = (Button) this.findViewById(R.id.act_pick_to_sort_btn_continue);
        this.btnMissing = (Button) this.findViewById(R.id.act_pick_to_sort_btn_missing);

        if (_BaseApplication.getGlobalSetting().getIsMultiScan() == 0) {
            this.layoutQty.setVisibility(View.GONE);
        }
        Intent intent = this.getIntent();
        if (intent != null) {
            waveId = intent.getLongExtra("id", 0L);
        } else {
            Toast.makeText(this, R.string.dialog_msg_para_error, Toast.LENGTH_SHORT).show();
            this.finish();
            return;
        }

        this.getNextRecord();

        //文本框事件
        List<EditText> ets = ViewUtils.getDescendants(this, EditText.class, false);
        for (final EditText item : ets) {
            if (item.isEnabled() == true && item.getVisibility() == View.VISIBLE) {
                item.setSelectAllOnFocus(true);//获取焦点全选
                item.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                            return onEnterDownEditText(v);
                        }

                        return false;
                    }
                });
                item.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            return onEnterDownEditText(v);
                        }
                        return false;
                    }
                });
                item.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (true == hasFocus) {
                            selectEt = item;
                        }
                    }
                });
            }
        }

        //按钮事件
        this.btnContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (true == checkSubmit(1)) {
                    int pickedQty = Integer.parseInt(txtPickedQty.getText().toString().trim());
                    pickUp(pickedQty);
                }
            }
        });
        this.btnMissing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (true == checkSubmit(2)) {
                    pickUp(0);
                }
            }
        });
    }

    private void getNextRecord() {
        Map<String, String> paras = new HashMap<String, String>();
        paras.put("id", this.waveId + "");
        paras.put("type", "1");//0=边拣边分 1=先拣后分 2=按单拣货
        get(ServicePort.getUrl(ServicePort.ShipPickWave), paras, new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                try {
                    ResponseResult result = new ResponseResult();
                    result = result.parseJson(s);
                    if (result != null && result.getSuc() == true) {

                        PickShipOrderModel model = new PickShipOrderModel();
                        model = model.parseJson(result.getResult().toString());

                        txtSpecLocationNo.setText(model.getLocationNo());
                        txtNextLocationNo.setText(model.getNextLocationNo());
                        txtSpecBarcode.setText(model.getBarcode());
                        txtItemName.setText(model.getItemName());
                        txtPickingQty.setText(model.getAvailableQty() + "");

                        shipmentId = model.getShipmentId();
                        skuId = model.getSkuId();
                    } else {
                        String message = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        DialogUtils.showOK(PickToSortActivity.this, getResources().getString(R.string.title_text_exception), message, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                PickToSortActivity.this.finish();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    DialogUtils.showOK(PickToSortActivity.this, getResources().getString(R.string.title_text_exception), e.getMessage(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            PickToSortActivity.this.finish();
                        }
                    });
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                DialogUtils.showOK(PickToSortActivity.this, getResources().getString(R.string.title_text_exception), s, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PickToSortActivity.this.finish();
                    }
                });
            }
        }, 1);
    }

    /**
     * 按下回车
     *
     * @param view
     * @return
     */
    private boolean onEnterDownEditText(View view) {
        if (view.getId() == this.txtPickCarNo.getId()) {
            isValidContainer();
            return true;
        } else if (view.getId() == this.txtRealLocationNo.getId()) {
            isValidLocation();
            return true;
        } else if (view.getId() == this.txtItemBarcode.getId()) {
            isValidBarcode();
            return true;
        } else if (view.getId() == this.txtPickedQty.getId()) {
            isValidPickedQty();
            return true;
        }

        return false;
    }

    private void isValidContainer() {
        if (true == TextUtils.isEmpty(this.txtPickCarNo.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_pick_car_no_not_null), this.txtPickCarNo);
        } else {
            Map<String, String> data = new HashMap<String, String>();
            data.put("waveId", this.waveId + "");
            data.put("containerNo", this.txtPickCarNo.getText().toString().trim());
            data.put("type", "1");
            get(ServicePort.getUrl(ServicePort.ShipPickContainer), data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            //拣货车ID
                            containerId = Long.parseLong(result.getResult().toString());

                            txtRealLocationNo.clearFocus();
                            txtRealLocationNo.setFocusable(true);
                            txtRealLocationNo.setFocusableInTouchMode(true);
                            txtRealLocationNo.requestFocus();
                            txtRealLocationNo.setCursorVisible(true);
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        showDialog(errorMsg, txtPickCarNo);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    showDialog(s, txtPickCarNo);
                }
            }, 1);
        }
    }

    private void isValidLocation() {
        if (true == TextUtils.isEmpty(this.txtRealLocationNo.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_location_no_not_null), txtRealLocationNo);
        } else if (false == this.txtRealLocationNo.getText().toString().trim().equals(txtSpecLocationNo.getText().toString().trim())) {
            showDialog(getResources().getString(R.string.dialog_msg_location_no_error), txtRealLocationNo);
        } else {
            Map<String, String> data = new HashMap<String, String>();
            data.put("locationNo", this.txtRealLocationNo.getText().toString().trim());
            get(ServicePort.getUrl(ServicePort.DirectMoveFromLocation), data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            locationId = Long.parseLong(result.getResult().toString());

                            txtItemBarcode.clearFocus();
                            txtItemBarcode.setFocusable(true);
                            txtItemBarcode.setFocusableInTouchMode(true);
                            txtItemBarcode.requestFocus();
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        showDialog(errorMsg, txtRealLocationNo);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    showDialog(s, txtRealLocationNo);
                }
            }, 1);
        }
    }

    private void isValidBarcode() {
        if (true == TextUtils.isEmpty(this.txtItemBarcode.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_item_barcode_not_null), txtItemBarcode);
        } else if (false == this.txtItemBarcode.getText().toString().trim().equals(this.txtSpecBarcode.getText().toString().trim())) {
            showDialog(getResources().getString(R.string.dialog_msg_item_barcode_error), txtItemBarcode);
        } else {
            if (layoutQty.getVisibility() == View.VISIBLE) {
                txtPickedQty.requestFocus();
            } else {
                pickUp(Integer.parseInt(txtPickedQty.getText().toString().trim()));
            }
        }
    }

    private void isValidPickedQty() {
        if (TextUtils.isEmpty(this.txtPickedQty.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_picked_qty_not_null), txtPickedQty);
        } else {
            int pickingQty = Integer.parseInt(this.txtPickingQty.getText().toString().trim());
            int pickedQty = Integer.parseInt(this.txtPickedQty.getText().toString().trim());
            if (pickedQty <= 0) {
                showDialog(getResources().getString(R.string.dialog_msg_picked_qty_smaller), txtPickedQty);
            } else if (pickedQty > pickingQty) {
                showDialog(getResources().getString(R.string.dialog_msg_picked_qty_bigger), txtPickedQty);
            } else {
                pickUp(pickedQty);
            }
        }
    }


    private void pickUp(int pickedQty) {
        progressDialog.show(getFragmentManager(), this.toString());
        JSONObject data = null;
        try {
            data = new JSONObject();
            data.put("isNeedRepick", "1");
            data.put("type", "1");
            data.put("waveId", this.waveId);
            data.put("shipmentId", this.shipmentId);
            data.put("containerId", this.containerId);
            data.put("locationNo", this.txtRealLocationNo.getText().toString().trim());
            data.put("locationId", this.locationId);
            data.put("skuId", this.skuId);
            data.put("barcode", this.txtItemBarcode.getText().toString().trim());
            data.put("qty", pickedQty);
        } catch (Exception e) {
            e.printStackTrace();
        }
        put(ServicePort.getUrl(ServicePort.ShipPickInsert), data, new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                String errorMsg = null;
                try {
                    ResponseResult result = new ResponseResult();
                    result = result.parseJson(s);
                    if (result != null && result.getSuc() == true) {
                        // 提示下一笔记录
                        getNextRecord();
                        txtRealLocationNo.setText("");
                        txtItemBarcode.setText("");
                        txtPickedQty.setText("1");


                        shipmentId = "";
                        locationId = 0L;
                        skuId = 0L;

                        txtRealLocationNo.requestFocus();

                        //拣货了 就不允许换小车了
                        if (txtPickCarNo.getText().toString().trim().length() > 0) {
                            txtPickCarNo.setEnabled(false);
                        }
                        progressDialog.dismiss();
                        return;
                    } else {
                        errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    errorMsg = e.getMessage();
                }

                if (false == TextUtils.isEmpty(errorMsg)) {
                    progressDialog.dismiss();
                    if (txtPickCarNo.isEnabled() == true) {
                        showDialog(errorMsg, txtPickCarNo);
                    } else {
                        showDialog(errorMsg, txtRealLocationNo);
                    }
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                progressDialog.dismiss();
                if (txtPickCarNo.isEnabled() == true) {
                    showDialog(s, txtPickCarNo);
                } else {
                    showDialog(s, txtRealLocationNo);
                }
            }
        }, 1);
    }

    private boolean checkSubmit(int submitType) {
        if (this.containerId == 0L) {
            showDialog(getResources().getString(R.string.dialog_msg_pick_car_no_not_null), this.txtPickCarNo);
            return false;
        } else if (this.locationId == 0L) {
            showDialog(getResources().getString(R.string.dialog_msg_pick_car_no_not_null), this.txtRealLocationNo);
            return false;
        } else if (false == this.txtSpecBarcode.getText().toString().trim().equals(this.txtItemBarcode.getText().toString().trim())) {
            showDialog(getResources().getString(R.string.dialog_msg_item_barcode_error), this.txtItemBarcode);
            return false;
        }
        if (submitType == 1) {
            if (TextUtils.isEmpty(this.txtPickedQty.getText().toString())) {
                showDialog(getResources().getString(R.string.dialog_msg_picked_qty_not_null), txtPickedQty);
            } else {
                int pickingQty = Integer.parseInt(this.txtPickingQty.getText().toString().trim());
                int pickedQty = Integer.parseInt(this.txtPickedQty.getText().toString().trim());
                if (pickedQty <= 0) {
                    showDialog(getResources().getString(R.string.dialog_msg_picked_qty_smaller), txtPickedQty);
                    return false;
                } else if (pickedQty > pickingQty) {
                    showDialog(getResources().getString(R.string.dialog_msg_picked_qty_bigger), txtPickedQty);
                    return false;
                } else {
                    //
                }
            }
        }

        return true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (this.selectEt != null) {
            switch (requestCode) {
                case ScanTypeConstants.SCAN_BAR_CODE:
                    if (resultCode == RESULT_OK) {
                        Bundle bundle = data.getExtras();
                        this.selectEt.setText(bundle.getString(Intents.Scan.RESULT, ""));
                        this.selectEt.requestFocus();
                        onEnterDownEditText(this.selectEt);
                    }
                default:
                    break;
            }
        }
    }

    @Override
    public int getTopNameResId() {
        return R.string.title_text_pick_to_sort;
    }

}